package com.stars.easyms.rest.lock;

import com.stars.easyms.base.util.ApplicationContextHolder;
import com.stars.easyms.rest.bean.RestLockInfo;
import com.stars.easyms.rest.exception.RestRuntimeException;
import com.stars.easyms.rest.manager.EasyMsRestRedisManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>className: EasyMsRestLock</p>
 * <p>description: EasyMs的rest加锁类</p>
 *
 * @author guoguifang
 * @version 1.2.2
 * @date 2019-07-12 13:36
 */
public final class EasyMsRestLock {

    private static final Logger logger = LoggerFactory.getLogger(EasyMsRestLock.class);

    private static final ThreadLocal<RestLockInfo> CURRENT_THREAD_REST_LOCK_INFO = new ThreadLocal<>();

    private EasyMsRestRedisManager easyMsRestRedisManager;

    /**
     * 获取锁
     */
    public void tryRestLock(RestLockInfo restLockInfo) {
        if (easyMsRestRedisManager != null) {
            String restLockName;
            if (restLockInfo != null && StringUtils.isNotBlank(restLockName = restLockInfo.getLockName())) {
                boolean lockFlag = easyMsRestRedisManager.getLock(restLockName, restLockInfo.getExpireSecond(),
                        restLockInfo.getTimeout(), restLockInfo.getRetryInterval(), logger);
                if (!lockFlag) {
                    String lockFailMsg;
                    if (StringUtils.isBlank(lockFailMsg = restLockInfo.getLockFailMsg())) {
                        lockFailMsg = "";
                    }
                    throw new RestRuntimeException(lockFailMsg);
                }
                CURRENT_THREAD_REST_LOCK_INFO.set(restLockInfo);
            }
        }
    }

    /**
     * 释放锁
     */
    public void releaseRestLock() {
        if (easyMsRestRedisManager != null) {
            RestLockInfo restLockInfo = CURRENT_THREAD_REST_LOCK_INFO.get();
            if (restLockInfo != null) {
                easyMsRestRedisManager.unlock(restLockInfo.getLockName());
                CURRENT_THREAD_REST_LOCK_INFO.remove();
            }
        }
    }

    public EasyMsRestLock() {
        this.easyMsRestRedisManager = ApplicationContextHolder.getBean(EasyMsRestRedisManager.class);
    }
}